#include <iostream>
#include <cmath>
using namespace std;

// 符号函数
double sgn(double y) {
    return (y > 0) ? 1 : ((y < 0) ? -1 : 0);
}

// 才能基函数
double phi3(double y) {
    return abs(y) * sin(M_PI * y);
}

// 导数 d(phi3)/dy
double d_phi3_dy(double y) {
    return sgn(y) * (sin(M_PI * y) + M_PI * y * cos(M_PI * y));
}

// 数值求解 y 从 p （牛顿法）
double inverse_y_from_p(double p, double tolerance = 1e-6, int max_iter = 100) {
    double y = 1.0; // 初始猜测
    for (int i = 0; i < max_iter; ++i) {
        double current_p = d_phi3_dy(y);
        if (fabs(current_p - p) < tolerance) break;
        // 计算二阶导数用于牛顿法更新
        double second_derivative = M_PI * (2 * cos(M_PI * y) - M_PI * y * sin(M_PI * y));
        y -= (current_p - p) / second_derivative;
    }
    return y;
}

// 勒让德变换
double legendreTransform(double p) {
    double y = inverse_y_from_p(p);
    return p * y - phi3(y);
}

int main() {
    double p = 1.0; // 输入动量 p
    cout << "勒让德变换结果: " << legendreTransform(p) << endl;
    return 0;
}